<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>文件上传页面</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 50px;
        }
        h2 {
            color: #333;
        }
        form {
            margin-bottom: 20px;
        }
        #uploadResult a {
            color: blue;
            text-decoration: none;
        }
        #uploadResult a:hover {
            text-decoration: underline;
        }
        .error {
            color: red;
        }
        .success {
            color: green;
        }
    </style>
</head>
<body>
<h2>文件上传</h2>
<form id="uploadForm" action="/UploadServlet" method="POST" enctype="multipart/form-data">
    选择要上传的文件：<input type="file" name="file" id="file" required />
    <button type="button" onclick="uploadFile()">上传文件</button>
</form>

<div id="uploadResult" style="margin-top: 10px;"></div>

<script>
    function uploadFile() {
        let formData = new FormData();
        let fileInput = document.getElementById("file");
        let file = fileInput.files[0];

        if (!file) {
            $("#uploadResult").html('<span class="error">请选择文件！</span>');
            return;
        }

        formData.append("file", file);

        $.ajax({
            url: "/UploadServlet",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                console.log("Server response:", response);
                if (response.status === "success" && response.filePath) {
                    $("#uploadResult").html(
                        '<span class="success">上传成功！文件路径：</span><a href="' + response.filePath + '" target="_blank">' + response.filePath + '</a>'
                    );
                } else {
                    $("#uploadResult").html('<span class="success">上传成功，但文件路径为空</span>');
                }
            },
            error: function(xhr, status, error) {
                console.error("Error:", error);
                $("#uploadResult").html('<span class="error">文件上传失败：' + (xhr.responseText || error) + '</span>');
            }
        });
    }
</script>
</body>
</html>



